import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

/**
 * Created by WeiZehao on 16/12/3.
 * This class is to send and receive Emails.
 */

public class EmailManager
{
    private static String myEmailAddress = "whu_weizehao@sina.com";
    private static String myEmailPassword = "19960816";
    private static String myEmailSMTP = "smtp.sina.com";

    private Session session;
    private Transport transport;
    private Store store;
    private Properties properties;
    private MimeMessage message;
    private StringBuffer sentence;

    /**
     *
     * @param choice If choice == 1, this object is to send email.
     *               Else, it's to receive email.
     * @throws Exception
     */
    public EmailManager(int choice) throws Exception
    {
        if(choice == 1)
        {
            initForSend();
        }
        else
        {
            initForReceive();
        }
    }

    /**
     * if sending messages, you need this method to initialize the object.
     * @throws Exception
     */
    private void initForSend() throws Exception
    {
        properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");  // protocol
        properties.setProperty("mail.host", myEmailSMTP);           // SMTP address
        properties.setProperty("mail.smtp.auth", "true");

        session = Session.getDefaultInstance(properties);
        session.setDebug(true);
    }

    /**
     * if receiving messages, you need this method to initialize the object.
     * @throws Exception
     */
    private void initForReceive() throws Exception
    {
        properties = new Properties();
        properties.setProperty("mail.store.protocol", "pop3");      // protocol
        properties.setProperty("mail.pop3.port", "110");
        properties.setProperty("mail.pop3.host", "pop.sina.com");   // POP3 address

        session = Session.getDefaultInstance(properties);
        session.setDebug(false);
    }

    /**
     * This method can return a Message object waiting to be sent.
     * @param session a Session object
     * @param sender sender's email address
     * @param receivers an array containing receivers' email address
     * @return a MimeMessage object
     * @throws Exception
     */
    private MimeMessage getMessage(Session session, String sender, ArrayList<String> receivers) throws Exception
    {
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender, "WeiZehao", "UTF-8"));

        for(int i = 0; i < receivers.size(); i++)
        {
            message.addRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(receivers.get(i), "someone", "UTF-8"));
        }

        message.setSubject("I want to ask a question", "UTF-8");
        message.setContent("Do you want to go abroad for further study?", "text/html;charset=UTF-8");
        message.setSentDate(new Date());

        message.saveChanges();
        return message;
    }

    /**
     * Extra credits
     * This method can return a complicated Message object with image and attachment.
     * @param session a Session object
     * @param sender sender's email address
     * @param receivers an array containing receivers' email address
     * @return  a MimeMessage object with image and attachment
     * @throws Exception
     */
    private MimeMessage getMutiMessage(Session session, String sender, ArrayList<String> receivers) throws Exception
    {
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender, "WeiZehao", "UTF-8"));

        // set receivers' address
        for(int i = 0; i < receivers.size(); i++)
        {
            message.addRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(receivers.get(i), "someone", "UTF-8"));
        }

        // main body of the email
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("Do you like the movie your name ?<br><img src='cid:A'>","text/html;charset=UTF-8");

        // create image in the main body part
        MimeBodyPart img = new MimeBodyPart();
        DataHandler dh1 = new DataHandler(new FileDataSource("doc/your_name.jpg"));
        img.setDataHandler(dh1);
        img.setContentID("A");

        // create attachment
        MimeBodyPart attachment = new MimeBodyPart();
        DataHandler dh2 = new DataHandler(new FileDataSource("doc/attachmentTest.txt"));
        attachment.setDataHandler(dh2);
        String name = dh2.getName();
        attachment.setFileName(MimeUtility.encodeText(name));

        // combine text part and image part
        MimeMultipart part1 = new MimeMultipart();
        part1.addBodyPart(img);
        part1.addBodyPart(text);
        part1.setSubType("related");

        MimeBodyPart content = new MimeBodyPart();
        content.setContent(part1);

        // combine main body part and attachment part
        MimeMultipart part2 = new MimeMultipart();
        part2.addBodyPart(content);
        part2.addBodyPart(attachment);
        part2.setSubType("mixed");

        message.setContent(part2);
        // set date
        message.setSentDate(new Date());
        message.saveChanges();
        return message;
    }

    /**
     * Send the Email to the receivers.
     * @param choice If choice == 1, it will send simple email.
     *               Else, it will send complicated email with image and attachment.
     * @throws Exception
     */
    public void sendMessage(int choice) throws Exception
    {
        // get receivers' address from database
        Database database = new Database();
        ResultSet resultSet = database.getData();
        ArrayList<String> receivers = new ArrayList();
        while(resultSet.next())
        {
            receivers.add(resultSet.getString(1));
        }

        if(choice == 1)
        {
            message = getMessage(session, myEmailAddress, receivers);
        }
        else
        {
            message = getMutiMessage(session, myEmailAddress, receivers);
        }

        transport = session.getTransport();
        transport.connect(myEmailAddress, myEmailPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * Get the Emails from my Email inbox.
     * @return an array of messages from inbox
     * @throws Exception
     */
    public Message[] receiveMessage() throws Exception
    {
        store = session.getStore("pop3");
        store.connect(myEmailAddress, myEmailPassword);

        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Message[] messages = folder.getMessages();
        return messages;
    }

    /**
     * Parse all the information of the Email.
     * Analyse the meaning of the response.
     * Print all the information.
     * @param messages an array of messages from inbox
     * @throws Exception
     */
    public void analyseMessage(Message[] messages) throws Exception
    {
        String[] posiSet = getPositiveSet();
        String[] negaSet = getNegativeSet();
        boolean isJudge = false;

        for(int i = 0; i < messages.length; i++)
        {
            System.out.printf("解析第%d封邮件", i+1);
            System.out.println();

            message = (MimeMessage) messages[i];
            System.out.println("主题: " + message.getSubject());
            System.out.println("发件人: " + decodeFrom(message));

            sentence = new StringBuffer(30);
            // parse content of the Email
            parseContent(message, sentence);
            String newSentence = sentence.toString();
            String[] str = newSentence.split("<");
            newSentence = str[0];
            System.out.println("邮件内容：" + newSentence);

            /*Semantic Part*/
            for(int j = 0; j < posiSet.length; j++)
            {
                // To decide whether the answer is positive.
                if(newSentence.indexOf(posiSet[j]) != -1)
                {
                    System.out.println("The meaning of the response： " +
                            "He/She wants to go abroad for further study");
                    isJudge = true;
                    break;
                }
            }

            for(int j = 0; j < negaSet.length; j++)
            {
                // To decide whether the answer is negative.
                if(newSentence.indexOf(negaSet[j]) != -1)
                {
                    System.out.println("The meaning of the response： " +
                            "He/She doesn't want to go abroad for further study");
                    isJudge = true;
                    break;
                }
            }

            if(isJudge == false)
            {
                System.out.println("Sorry, the meaning of the response can't be understood.");
            }

            System.out.println("-------------------------------------");
        }// end for
    }// end method

    /**
     * For semantic part
     * Return an array which consists of some possible words showing positive attitude.
     * @return an array of String
     */
    private String[] getPositiveSet()
    {
        String[] positiveAnswerSet = new String[8];
        positiveAnswerSet[0] = "Yes";
        positiveAnswerSet[1] = "Sure";
        positiveAnswerSet[2] = "Of course";
        positiveAnswerSet[3] = "Absolutely";
        positiveAnswerSet[4] = "Definitely";
        positiveAnswerSet[5] = "Certainly";
        positiveAnswerSet[6] = "sure";
        positiveAnswerSet[7] = "certain";
        return positiveAnswerSet;
    }

    /**
     * For semantic part
     * Return an array which consists of some possible words showing negative attitude.
     * @return an array of String
     */
    private String[] getNegativeSet()
    {
        String[] negativeAnswerSet = new String[4];
        negativeAnswerSet[0] = "No";
        negativeAnswerSet[1] = "not";
        negativeAnswerSet[2] = "don't";
        negativeAnswerSet[3] = "can't";
        return negativeAnswerSet;
    }

    /**
     * Get Email sender's information from message.
     * @param message
     * @return email sender's address
     * @throws Exception
     */
    private String decodeFrom(MimeMessage message) throws Exception
    {
        Address[] address = message.getFrom();

        InternetAddress internetAddress = (InternetAddress) address[0];
        String sender = internetAddress.getPersonal();
        sender = MimeUtility.decodeText(sender);

        String info = sender + "<" + internetAddress.getAddress() + ">";
        return info;
    }

    /**
     * Parse content of the Email.
     * @param part Message object
     * @param content StringBuffer to store email's content
     * @throws Exception
     */
    private void parseContent(Part part, StringBuffer content) throws Exception
    {
        boolean isHasAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isHasAttach)
        {
            content.append(part.getContent().toString());
        }
        else if (part.isMimeType("message/rfc822"))
        {
            parseContent((Part)part.getContent(),content);
        }
        else if (part.isMimeType("multipart/*"))
        {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++)
            {
                BodyPart bodyPart = multipart.getBodyPart(i);
                parseContent(bodyPart,content);
            }
        }
    }
}